package com.zy.explore.generator.interfaces.facade.v1;

import com.zy.explore.generator.infrastructure.core.enums.PersistLayerFrameworkTypeEnum;
import com.zy.explore.generator.infrastructure.core.frm.BrickInfoFrm;
import com.zy.explore.generator.infrastructure.core.service.TableGeneratorService;
import com.zy.explore.generator.infrastructure.core.util.DataBeanUtil;
import com.zy.explore.generator.infrastructure.exception.MessageCode;
import com.zy.explore.generator.interfaces.frm.CustomFrm;
import com.zy.explore.generator.interfaces.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * description 表代码生成器
 *
 * @author 🇨🇳中国印🇨🇳
 * @date 2021年06月05日 13:54
 */
@Slf4j
@Api(tags = "Java后端表代码生成控制器")
@RestController
@RequestMapping("/table")
public class TableGeneratorController {

    @Resource
    private TableGeneratorService tableGeneratorService;

    /**
     * 生成代码
     */
    @ApiOperation("根据表名逆向生成代码")
    @GetMapping("/genCode")
    public ResultVO<String> genCode(@SpringQueryMap @Validated CustomFrm frm, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            FieldError fieldError = result.getFieldError();
            String tableNameListField = "tableNameList";
            if (fieldError != null && Objects.equals(fieldError.getField(), tableNameListField)) {
                throw MessageCode.TABLE_NAME_EMPTY_ERROR.toException();
            }
        }
        BrickInfoFrm brickInfoFrm = DataBeanUtil.copyOf(frm, BrickInfoFrm.class, true);
        if (frm.getPersistLayerFrameworkType() == PersistLayerFrameworkTypeEnum.JPA) {
            brickInfoFrm.setUseJpa(true).setUseTkMybatis(false).setUseMybatisPlus(false);
        } else if (frm.getPersistLayerFrameworkType() == PersistLayerFrameworkTypeEnum.TK_MYBATIS) {
            brickInfoFrm.setUseJpa(false).setUseTkMybatis(true).setUseMybatisPlus(false);
        } else {
            brickInfoFrm.setUseJpa(false).setUseTkMybatis(false).setUseMybatisPlus(true);
        }
        try {
            // 生成表基础代码
            tableGeneratorService.genTableCode(brickInfoFrm);
            return ResultVO.getSuccess("生成成功");
        } catch (Exception e) {
            log.error("生成失败：", e);
            return ResultVO.getError(500, e.getMessage(), "生成失败");
        }
    }

}
